package com.leectrl.utils;

import com.leectrl.bean.LocalCacheItem;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;

import io.netty.util.internal.StringUtil;

public class LocalCacheManage {
    private static LocalCacheManage localCacheManage;
    private static ConcurrentHashMap<String, LocalCacheItem> keyValues=new ConcurrentHashMap<>();
    private LocalCacheManage(){

    }

    //单例
    public static LocalCacheManage getInstance(){
        if(localCacheManage==null){
            localCacheManage=new LocalCacheManage();
            Timer timer = new Timer();
            timer.scheduleAtFixedRate(new TimerTask() {
                public void run() {
                    Set<String> expiredKeys=new HashSet<>();

                    if(!keyValues.isEmpty()){
                        for(String key : keyValues.keySet()){
                            if(keyValues.get(key).getExpireTime()<=System.currentTimeMillis()){
                                expiredKeys.add(key);
                            }
                        }
                    }
                    if(!expiredKeys.isEmpty()){
                        for(String expiredKey : expiredKeys){
                            keyValues.remove(expiredKey);
                        }
                    }
                }
            }, 0, 1000);
        }
        return localCacheManage;
    }

    public boolean set(String key,String value,int cacheTime){
        if(StringUtil.isNullOrEmpty(key)||StringUtil.isNullOrEmpty(value)){
            return false;
        }
        long expireTime=System.currentTimeMillis()+cacheTime;
        if(cacheTime<=0){
            return false;
        }
        LocalCacheItem localCacheItem=new LocalCacheItem(value,expireTime);
        keyValues.put(key,localCacheItem);
        return true;
    }

    public String get(String key){
        if(StringUtil.isNullOrEmpty(key)){
            return null;
        }
        if(!keyValues.containsKey(key)){
            return null;
        }
        LocalCacheItem localCacheItem=keyValues.get(key);
        return localCacheItem.getValue();
    }

    public boolean delete(String key) {
        if (StringUtil.isNullOrEmpty(key)) {
            return false;
        }
        if (!keyValues.containsKey(key)) {
            return false;
        }
        keyValues.remove(key);
        return true;
    }
}
